package com.acme.iolab.filesend.io;


import com.acme.iolab.filesend.FileServer;
import com.acme.iolab.filesend.IntToByteArrayConverter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class IOFileServer extends FileServer {

    final ServerSocket serverSocket;

    public IOFileServer(int port) throws IOException {
        super(port);
        serverSocket = new ServerSocket(port);
    }

    public void process(String savePath) throws IOException {
        try (
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                FileOutputStream fileOutputStream = new FileOutputStream(savePath)) {

            System.out.println("Accepted connection.");
            long start = System.currentTimeMillis();

            final byte[] sizeBuffer = new byte[4];
            inputStream.read(sizeBuffer, 0, 4);
            int size = IntToByteArrayConverter.convertBack(sizeBuffer);
            final byte[] buffer = new byte[size];

            int n;
            int read = 0;
            System.out.println("Start receiving file...");
            while (read < size) {
                n = inputStream.read(buffer);
                read += n;
                fileOutputStream.write(buffer, 0, n);
            }

            System.out.println("Filed received in: " + (System.currentTimeMillis() - start));
            out.println("completed");
            System.out.println("Completed.");
        }
    }
}

